let DifInfo2Sql = function () {
}

DifInfo2Sql.prototype.dif2sql = function (GetRecordDifRsp, SynReq) {
    /**
     * limit - id
     *
     *单个参数
     * 0 全部
     * 1356 id=1356
     *
     * 两个参数
     * 1356 1789  id(1356~1789)
     */
    let limitId = [SynReq.startId, SynReq.endId];//起始id 终止id
    if (SynReq.startId==0) {//
        limitId[0]=1;
        limitId[1]=9999;
    }else if(SynReq.endId==0){//只传了一个参数
        limitId[1] = limitId[0];
    }


    let sqls = [];
    let DbId = ['', 'station_id', 'config_id'];//同步 difType 下标
    let DbTable = ['', global.configs.mysqlDbInfo.StationTable, global.configs.mysqlDbInfo.RulesTable];
    let jsonKeys = ['query_js', 'config_details']

    for (let i = 0; i < GetRecordDifRsp.vDifRecord.length; i++) {
        let DifRecord = GetRecordDifRsp.vDifRecord.value[i];

        let difType = DifRecord.difType;//0-all/1-sta/2-rule

        let difId = parseInt(DifRecord.id) ;
        //判断是否在limit-id里 //
        if ((difId >= limitId[0] && difId <= limitId[1]) || (difType == 0)) {
            /**
             * 判断是update or insert
             * difType==1 && difdetail.realDetail['station_id']==''
             * difType==2 && difdetail.realDetail['config_id']==''
             * difType==0
             */


            let insertKeys = [];
            let insertValues = [];
            let updateInfos = [];
            let flag = 0;//0-insert/1-update

            //生成sql
            for (let key in DifRecord.mDifDetail.value) {
                if (jsonKeys.indexOf(key) + 1) {
                    DifRecord.mDifDetail.value[key].testDetail = DifRecord.mDifDetail.value[key].testDetail.replace(/\'/g, '\\\'');
                }

                if (DifRecord.mDifDetail.value[DbId[difType]]) {//insert
                    insertKeys.push(`\`${key}\``);
                    insertValues.push(`'${DifRecord.mDifDetail.value[key].testDetail}'`);
                } else {//update
                    let info = `\`${key}\`='${DifRecord.mDifDetail.value[key].testDetail}'`;
                    updateInfos.push(info);
                    flag = 1;
                }
            }
            let sql = [`INSERT INTO \`${DbTable[difType]}\`(${insertKeys.toString()})VALUES(${insertValues.toString()})`,
                `UPDATE \`${DbTable[difType]}\`SET ${updateInfos.toString()} WHERE \`${DbId[difType]}\`=${DifRecord.id}`]
            sqls.push(sql[flag]);
        }
    }
    return sqls;
}
module.exports = DifInfo2Sql